<script setup>
import {showToast} from "vant";
import {nextTick, onMounted, ref} from "vue";
import {currentUser} from "@/App.vue";
import request from "@/assets/js/mobileRequest";
import qs from "qs";
import { useRouter } from 'vue-router';

const router = useRouter();

const onClickLeft = () => history.back('success');

const onSubmit = (values) => {
  console.log('submit', values);
};
const order = ref({
  orderId: '',
  riderId: '',
  userId: '',
  creationTime: '',
  acceptTime: '',
  endTime: '',
  startLocation: '',
  endLocation: '',
  DetailedStartLocation:'',
  DetailedEndLocation:'',
  orderType: null,
  orderPrice: '',
  orderStatus: '',
  orderReview: '',
  orderRate: '',
  orderDescription: '',
  orderTitle: ''
});

const columns = [
  { text: '打饭', value: '打饭' },
  { text: '拿外卖', value: '拿外卖' },
  { text: '送厕纸', value: '送厕纸' },
  { text: '拿快递', value: '拿快递' },
  { text: '跑腿', value: '跑腿' },
];

const place = [
  {text:'建筑工程学院',value:'建筑工程学院'},
  {text:'学生事务中心',value:'学生事务中心'},
  {text:'办公大楼',value:'办公大楼'},
  {text:'电力楼',value:'电力楼'},
  {text:'计算机重点实验室',value:'计算机重点实验室'},
  {text:'管理与经济学院',value:'管理与经济学院'},
  {text:'公教楼',value:'公教楼'},
  {text:'计算机中心',value:'计算机中心'},
  {text:'医学院',value:'医学院'},
  {text:'恒园',value:'恒园'},
  {text:'怡园宿舍区',value:'怡园宿舍区'},
  {text:'红土会堂',value:'红土会堂'},
  {text:'憬园',value:'憬园'},
  {text:'昆明理工大学呈贡校区校医院',value:'昆明理工大学呈贡校区校医院'},
];

const showType = ref(false);
const onConfirmType = ({ selectedOptions }) => {
  order.value.orderType = selectedOptions[0]?.text;
  showType.value = false;
};

const showStartLocation = ref(false);
const onConfirmStartLocation = ({ selectedOptions }) => {
  order.value.startLocation = selectedOptions[0]?.text;
  showStartLocation.value = false;
};

const showEndLocation = ref(false);
const onConfirmEndLocation = ({ selectedOptions }) => {
  order.value.endLocation = selectedOptions[0]?.text;
  showEndLocation.value = false;
};

const userInfo = ref({
  username:'test',
  description:'吾心吾行澄如明镜，所作所为皆是正义。吾心吾行澄如明镜，所作所为皆是正义。',
  level: 10,
  gender: '男',
  avatarImgUrl:'',
  userId:''
});

const serOrder = ()=>{
  console.log(order.value);
  order.value.userId = userInfo.value.userId;
  order.value.orderStatus = '未支付';
  let data = qs.stringify(order.value);
  console.log(data);
  request.post(BASE_URL + '/v1/order/insert', data).then((response) => {
    if (response.data.code === 2000) {
      order.value = response.data.data;
      const orderId = order.value.orderId;
      router.push({ path: '/pay', query: { orderId } });
    }
  })
}

var coordtransform = require('coordtransform');

const loadPosition = () => {

  //如果该对象存在，那么地理位置服务可用。
  if ('geolocation' in navigator) {
    /* 地理位置服务可用 */
    var options = {
      enableHighAccuracy: true, //布尔值，表示系统是否使用最高精度来表示结果，注意，这会导致较慢的响应时间或者增加电量消耗（比如对于支持gps的移动设备来说）。如果值为false ，设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
      timeout: 5000, //它表明的是设备必须在多长时间（单位毫秒）内返回一个位置。默认直到获取到位置才会返回值。
      maximumAge: 0 //表明可以返回多长时间（即最长年龄，单位毫秒）内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置，而且必须去获取一个真实的当前位置。默认0
    }

    function success(position) {
      //position.coords (只读) 返回一个定义了当前位置的Coordinates对象。
      //position.timestamp (只读) 返回一个时间戳DOMTimeStamp， 这个时间戳表示获取到的位置的时间。
      var lat = position.coords.latitude //当前位置的纬度
      var lng = position.coords.longitude //当前位置精度
      console.log('位置:纬度：' + lat + "，经度：" + lng);
      let p = coordtransform.wgs84togcj02(lng, lat)
      p = coordtransform.gcj02tobd09(p[0], p[1])
      console.log('位置:纬度：' + coordtransform.gcj02tobd09(p[0], p[1]));
      request.get(BASE_URL + '/v1/position/location?x=' + p[0] + '&y=' + p[1]).then((response) => {
        if (response.data.code === 2000) {
          console.log(response.data.data);
          alert('位置:纬度：' + lat + "，经度：" + lng + response.data.data)
        }
      });
    };

    function error(err) {
      var errorType = ['您拒绝共享位置信息', '获取不到位置信息', '获取位置信息超时']
      console.log(errorType[err.code - 1])
    }

    navigator.geolocation.getCurrentPosition(success, error, options)
  } else {
    /* 地理位置服务不可用 */
    console.log('无法获取您的位置，请检查定位是否开启或刷新重试')
  }

  /*if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {
    alert("浏览器不支持地理定位。");
  }*/
};


onMounted(()=>{
  nextTick(() => {
    userInfo.value = currentUser.value;
    console.log(userInfo.value);
    loadPosition();
  })
})

</script>
<template>
  <van-nav-bar
      title="订单发起"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
  />
  <van-form @submit="onSubmit" label-align="right">
    <van-cell-group inset>
      <van-field
          v-model="order.orderPrice"
          required
          name="订单价格"
          label="订单价格"
          placeholder="订单价格"
          :rules="[{ required: true, message: '请填写订单价格' }]"
      />
      <van-field
          v-model="order.orderType"
          is-link
          readonly
          required
          name="picker"
          label="订单类型"
          placeholder="点击选择订单类型"
          @click="showType = true"
      />
      <van-popup v-model:show="showType" position="bottom">
        <van-picker
            :columns="columns"
            @confirm="onConfirmType"
            @cancel="showType = false"
        />
      </van-popup>
      <van-field
          v-model="order.startLocation"
          is-link
          readonly
          name="开始位置"
          label="开始位置"
          placeholder="点击选择位置"
          @click="showStartLocation = true"
      />
      <van-popup v-model:show="showStartLocation" position="bottom">
        <van-picker
            :columns="place"
            @confirm="onConfirmStartLocation"
            @cancel="showStartLocation = false"
        />
      </van-popup>
      <van-field
          v-model="order.DetailedStartLocation"
          name="详细地址"
          label="详细地址"
          placeholder="起始位置详细地址"
      />
      <van-field
          v-model="order.endLocation"
          is-link
          required
          readonly
          name="送达位置"
          label="送达位置"
          placeholder="点击选择位置"
          @click="showEndLocation = true"
      />
      <van-popup v-model:show="showEndLocation" position="bottom">
        <van-picker
            :columns="place"
            @confirm="onConfirmEndLocation"
            @cancel="showEndLocation = false"
        />
      </van-popup>
      <van-field
          v-model="order.DetailedEndLocation"
          name="详细地址"
          required
          label="详细地址"
          placeholder="送达位置详细地址"
          :rules="[{ required: true, message: '请填写详细地址' }]"
      />
      <van-field
          v-model="order.orderTitle"
          name="订单标题"
          label="订单标题"
          placeholder="订单标题"
      />
      <van-field
          v-model="order.orderDescription"
          rows="3"
          autosize
          required
          label="订单描述"
          type="textarea"
          maxlength="50"
          placeholder="请输入订单描述"
          show-word-limit
      />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="success" native-type="submit" @click="serOrder">
        订单确认
      </van-button>
    </div>
  </van-form>

</template>

<style scoped>

</style>